import { useState, useEffect } from "react";
import { withRouter } from "next/router";
import { DatePicker } from "antd";
import { queryCheckEmpty } from '@/utils';
import moment from "moment";
import Head from "@/components/Head";
import Tkd from "@/ssr/tkd";
// css
import styles from "@/styles/CommonList.module.scss";
// 组件
import Breadcrumb from "@/components/Breadcrumb";
import Pagination from '@/components/Pagination';
import ListItem from "@/pages_components/list/ListItem";
import HotProductPart from "@/pages_components/components/HotProductPart";
import Empty from '@/pages_components/list/Empty';
// ssr api
import { productList_SSR } from "@/ssr";

const { RangePicker } = DatePicker;
const dateFormat = "YYYY-MM-DD";
const pageType = '/hotel';

const Hotel = ({ router, list, total }) => {
  // 筛选条件，初始化
  const _filters = {
    roomTypes: [
      { label: "全部", value: "", chosen: true },
      { label: "标准间", value: 1 },
      { label: "大床房", value: 4 },
      { label: "家庭房", value: 3 },
      { label: "独栋/套房", value: 2 },
    ],
  };

  // 筛选
  const [filters, setFilters] = useState(_filters);

  let { query, query: { date='' } } = router;
  let today = moment().add(0, "days"),
      tomorrow = moment().add(1, "days");

  // 订房时间/关键字/房型
  const [dates, setDates] = useState([]);
  const [rangeTime, setRangeTime] = useState([today, tomorrow]);
  const [keywords, setKeywords] = useState("");
  const [roomType, setRoomType] = useState('');

  useEffect(() => {
    // 初始化，已筛选条件
    const params = Object.keys(query);
    if(params.length){
        params.forEach(key => {
            queryHandler(key, query[key]);
        })
    }
  }, []);

  // 通过nav切换回本页面第一页，去掉选中筛选
  useEffect(() => {
    if(router.asPath === router.pathname){
      setFilters(_filters);
      setRoomType('');
      setKeywords('');
      setRangeTime([today, tomorrow])
    }
  }, [router.asPath]);
 
  // 禁用开始时间(开始时间不能大于当前时间)
  function disabledDate(current) {
    const yesterday = moment().add(-1, "days");
    if (current <= yesterday) {
      return true;
    }
    if (!dates || dates.length === 0 || (dates[0] && current > dates[0])) {
      return false;
    }
    return true;
  }
  // 打开picker，重置日期
  function onOpenChange(open) {
    if (open) {
      setDates([]);
    }
  }
  // 已筛选条件
  function queryHandler(key, val) {
    switch(key){
      case 'r': {
        if(val){
          val.split(',').forEach(t => {
            choseFilter('roomTypes', t, true)
          })
        }
        break
      }
      case 'keyword': {
        setKeywords(val);
        break
      }
      case 'date': {
        if(date.includes('_')){
          const [start, end] = date.split('_');
          setRangeTime([moment(start), moment(end)]);
        }
        break
      }
    }
  }
  // 统一路由处理
  function routeHandler(isNow, _roomsType) {
    const _query = { ...query };
    const [startDate, endDate] = [
      moment(rangeTime[0]).format(dateFormat),
      moment(rangeTime[1]).format(dateFormat),
    ];
    const t = moment(today).format(dateFormat),
          tm = moment(tomorrow).format(dateFormat);
    if(!(startDate === t && endDate === tm)){
      _query['date'] = startDate + '_' + endDate;
    }else{
      _query['date'] = '';
    }
    _query['keyword'] = keywords;
    _query['r'] = isNow ? _roomsType : roomType;

    let newQuery = queryCheckEmpty(_query);
    router.push({
        pathname: pageType,
        query: {
            ...newQuery
        }
    })
  }
  // 筛选条件
  function choseFilter(key, value, init) {
    filters[key].forEach((f) => {
      if (!value) {
        if (!f.value) {
          f.chosen = true;
        }
        f.chosen = false;
      }
      if (!f.value && value) {
        f.chosen = false;
      }
      if (f.value == value) {
        f.chosen = !f.chosen;
      }
    });
    const _roomType = filters[key].filter(item => {
      return item.chosen && item.value
    }).map(item => item.value).toString();
    // 若未选择任何标签，默认跳回全部
    if(value && !_roomType){
      filters[key][0].chosen = true
    }
    setRoomType(_roomType);
    setFilters({ ...filters });
    !init && routeHandler(true, _roomType)
  }
  // 获取分页数据，处理筛选条件
  function doSearch() {
    routeHandler()
  }

  // 搜索条件 Component
  const Search = (
    <>
      <div>
        <span>入住/退房</span>
        <RangePicker
          className={styles["date-picker"]}
          placeholder={["入住时间", "退房时间"]}
          allowClear={false}
          format={dateFormat}
          value={rangeTime}
          disabledDate={disabledDate}
          onChange={(val) => setRangeTime(val)}
          onCalendarChange={(val) => setDates(val)}
          onOpenChange={onOpenChange}
        />
      </div>
      <div>
        <span>关键词</span>
        <input
          type="text"
          placeholder="酒店/关键词"
          value={keywords}
          onChange={(e) => setKeywords(e.target.value)}
        />
      </div>
      <span className={styles["search-btn"]} onClick={() => {doSearch()}}>搜索</span>
    </>
  );
  // 筛选条件 Component
  const Filters = (
    <>
      <dl>
        <dt>房型选择</dt>
        <dd>
          {
            filters.roomTypes.map((item) => <span 
                                              onClick={() => { choseFilter("roomTypes", item.value) }} 
                                              className={item.chosen ? styles["selected"] : ""} 
                                              key={item.value}
                                            >{item.label}</span>)
          }
        </dd>
      </dl>
    </>
  );
  
  return (
    <div className={styles["common-list-page"]}>
      {/* 标题/关键字/网页描述 */}
      <Head meta={Tkd[pageType]} />
      {/* 网页内容 */}
      <div className="max-content">
        {/* 面包屑 */}
        <Breadcrumb params={[{ name: "酒店住宿", url: pageType }]} />
        <div className={styles.cnt}>
          {/* 左侧 */}
          <div className={styles["cnt-left"]}>
            {/* 搜索 */}
            <div className={styles["hotel-search"]}>{Search}</div>
            {/* 筛选 */}
            <div className={[styles["filter"], styles["ticket"]].join(" ")}>
              {Filters}
            </div>
            {/* 列表 */}
            <div className={styles["pro-list"]}>
              {
                !list.length
                ? <Empty />
                : list.map((item) => <ListItem target={pageType} targetUrl={`${pageType}/${item.goodsId}.html` + (date ? `?date=${date}` : '')} data={item} key={item.goodsId} />)}
            </div>
            {/* 分页 */}
            <Pagination root={pageType} total={total} />
          </div>
          {/* 右侧，热门列表 */}
          <div className={styles["cnt-right"]}>
            <HotProductPart product="热门景区" target="/ticket" />
          </div>
        </div>
      </div>
    </div>
  );
};

// ssr 请求
Hotel.getInitialProps = async (ctx) => {
  const { pathname, query } = ctx;
  const { 
      ssr: list, 
      total
  } = await productList_SSR(pageType, { pathname, query });
  return { list, total }
};

export default withRouter(Hotel);